package cn.openea.perpartner.link.website;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.openea.perpartner.common.auth.entity.LoginBody;
import cn.openea.perpartner.common.core.exception.ServiceException;
import cn.openea.perpartner.common.redis.service.RedisCache;
import cn.openea.perpartner.link.constant.CommonConstants;
import cn.openea.perpartner.link.constant.enums.AppType;
import cn.openea.perpartner.link.util.UserContext;
import cn.openea.perpartner.link.web.entity.ShareLinkConfig;
import cn.openea.perpartner.link.web.service.IShareLinkConfigService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;

/**
 * @author ysk
 * @version 1.0.1
 * @Description TODO
 * @createTime 2023年04月07日 16:45:00
 */
@Slf4j
@Controller
public class WebsiteTemplateController {

    @Resource
    private IShareLinkConfigService shareLinkConfigService;
    @Resource
    private RedisCache redisCache;

    @RequestMapping("/")
    public ModelAndView index() {
        //1.获取用户登录信息
        ModelAndView modelAndView = new ModelAndView();
        LoginBody loginUser = UserContext.getLoginUser();
        modelAndView.addObject("loginUser", loginUser);
        modelAndView.setViewName("index");
        return modelAndView;
    }

    @GetMapping("/{key}")
    public ModelAndView jumpLink(@PathVariable String key) {
        ModelAndView modelAndView = new ModelAndView();
        ShareLinkConfig shareLinkConfig = shareLinkConfigService.findOneByKey(key);
        if (shareLinkConfig == null) {
            throw new ServiceException("分享链接不存在");
        }
        AppType appType = AppType.getByCode(shareLinkConfig.getAppType());
        if (appType == null) {
            throw new ServiceException("链接所属平台为空");
        }
        Integer number = redisCache.getNumber(CommonConstants.REDIS.REDIS_SHARE_LINK_VISITS_NUM + shareLinkConfig.getId());
        if (number == null) {
            // redis缓存点击量
            redisCache.setNumber(CommonConstants.REDIS.REDIS_SHARE_LINK_VISITS_NUM + shareLinkConfig.getId(), 0);
        }
        String getLinkTokenUrl = String.format(CommonConstants.WECHAT.GET_URL_LINK_ACCESS_TOKEN_URL, appType.getAppId(), appType.getSecret());
        String result = HttpUtil.get(getLinkTokenUrl);
        if (StringUtils.isBlank(result)) {
            throw new ServiceException("获取token失败");
        }
        JSONObject wxObject = JSON.parseObject(result);
        String accessToken = wxObject.getString("access_token");
        String getLinkUrl = String.format(CommonConstants.WECHAT.GET_URL_LINK_URL, accessToken);
        JSONObject paramMap = new JSONObject();
        paramMap.put("path", shareLinkConfig.getPagePath());
        HttpResponse rep = HttpRequest.post(getLinkUrl)
                .header("Content-Type", "application/json")
                .body(paramMap.toString()).execute();
        JSONObject res = JSON.parseObject(rep.body());
        if (!"0".equals(res.getString("errcode"))) {
            throw new ServiceException(res.getString("errmsg"));
        }
        String wxLinkURL = res.getString("url_link");
        // 将点击量保存导redis中
        redisCache.incrementNumber(CommonConstants.REDIS.REDIS_SHARE_LINK_VISITS_NUM + shareLinkConfig.getId());
        modelAndView.setViewName("redirect:" + wxLinkURL);
        return modelAndView;
    }
}
